<?php

namespace app\admin\controller;

use app\admin\controller\Main;
use app\commons\model\ActivityVideo;
use app\commons\model\CreateVideo;
use app\commons\model\Material;
use app\commons\model\Member as MemberModel;
use app\commons\model\MemberSale;
use app\commons\model\MemberVideo;
use app\commons\model\SaleCard;
use app\commons\model\SaleVerifyer;
use app\job\UploadFileVideo;
use redis\Redis;
use think\Controller;
use think\Db;
use app\commons\model\Sale as SaleModel;
use think\Exception;
use think\Queue;

class Sale extends Main
{

    public function index()
    {

        $_GPC = input();
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 1);
        $row = new SaleModel;
        if (isset($_GPC['member_id']) && $_GPC['member_id'] != '') {
            $row = $row->where('member_id', $_GPC['member_id']);
        }
        if (!empty($_GPC['title'])) {
            $row = $row->whereLike('title', "%{$_GPC['title']}%");
        }
        if (isset($_GPC['paytype']) && $_GPC['paytype'] != '') {
            $row = $row->where('paytype', $_GPC['paytype']);
        }
        if (isset($_GPC['status'])) {
            $row = $_GPC['status'] == '1' ? $row->where('endtime', '>', time()) : $row->where('endtime', '<', time());
        }
        $count = $row->count();
        $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
//        $data = $row->paginate($page);
        jsonpp($data, $count);
    }

    public function add()
    {

        if ($this->request->isPost()) {
            $_GPC['data'] = $this->data['data'];
            $token = check_formtoken();
            unset($_GPC['data']['token']);
            $member = pdo_get('member', array('id' => $_GPC['data']['member_id']));
            if(!$member) jsont(array('token' => $token), 1, '商家不存在！');
            if ($member['num'] != 0 && max($member['num'], 0) < $_GPC['data']['number']) {
                jsont(array('token' => $token), 1, '商家点数剩余：' . max($member['num'], 0) . '，扫码次数最多只能填写：' . max($member['num'], 0) . '！');
            }
            if ($member['num'] != 0 && $_GPC['data']['number'] == 0) {
                jsont(array('token' => $token), 1, '商家点数剩余：' . max($member['num'], 0) . '，扫码次数必须大于0！');
            }
            if ($member['sale_num'] != 0) {

                $sale_num = Db::name('sale')->where(array('member_id' => $_GPC['data']['member_id']))->count();
                if ($member['sale_num'] <= $sale_num) {
                    jsont(array('token' => $token), 1, '商家活动数量已满：' . $member['sale_num'] . '，不能添加新活动！');
                }
            }

            $alivideo = true;
            $_GPC['data']['createtime'] = time();
            $_GPC['data']['starttime'] = strtotime($_GPC['data']['starttime']);
            $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);
            $_GPC['data']['poster'] = isset($_GPC['data']['poster']) ? json_encode($_GPC['data']['poster']) : "";
            $_GPC['data']['video'] = isset($_GPC['data']['video']) ? json_encode($_GPC['data']['video']) : '';
            $_GPC['data']['replace'] = isset($_GPC['data']['replace']) ? json_encode($_GPC['data']['replace']) :'';
            $_GPC['data']['card'] = isset($_GPC['data']['card']) ? json_encode($_GPC['data']['card']) :'';
            $result = pdo_insert('sale', $_GPC['data']);
            if (!empty($result) || $result === 0) {
                if ($member['num'] != 0) {
                    $member['num'] = $member['num'] - $_GPC['data']['number'];
                    $member['num'] != 0 or $member['num'] = -1;
                    pdo_update('member', $member, array('id' => $member['id']));
                }
//                if ($alivideo) {
//                    $id = pdo_insertid('sale');
//                    asyn_http_get($this->request->domain(true) . 'web/alivideo?sale_id=' . $id);
//                }
                jsont(array('token' => $token), 0, '添加成功');
            } else {
                jsont(array('token' => $token), 1, '添加失败！');
            }
        }
        $data = array();
        return jsonp(get_upload_data($data));
    }


    /**
     * 活动详情
     * @return \think\response\Jsonp|void
     */
    public function show()
    {
        $_GPC['data'] = $this->data;
        $id = $this->data['id'];
        $data = pdo_get('sale', array('id' => $id));
        return jsonp($data);
    }

    public function edit()
    {
        $_GPC = $this->data;
        $id = $this->data['id'];
        $data = SaleModel::get($id);
        if ($this->request->isPost()) {
            try {
                $token = check_formtoken();
                unset($_GPC['data']['token']);
                $member = pdo_get('member', array('id' => $_GPC['data']['member_id']));
                if(!$member) throw new Exception('商户不存在！');
                if ($member['num'] != 0 && max($member['num'], 0) + $data['number'] < $_GPC['data']['number']) {
                    return jsont([], 1, '商家点数剩余：' . (max($member['num'], 0) + $data['number']) . '，扫码次数最多只能填写：' . (max($member['num'], 0) + $data['number']) . '！');
                }
                if ($member['num'] != 0 && $_GPC['data']['number'] == 0) {
                    return jsont([], 1, '商家点数剩余：' . (max($member['num'], 0) + $data['number']) . '，扫码次数必须大于0！');
                }

                $alivideo = true;
                $_GPC['data']['starttime'] = strtotime($_GPC['data']['starttime']);
                $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);

                //处理视频合成
                $createVideo = $_GPC['data']['video']['alivideo']['video_all'] ?? [];
                if (!empty($createVideo)) {
                    $createVideoAddData = [
                        'sale_id' => $data['id'],
                        'title' => $_GPC['data']['video']['alivideo']['title'] ?? '',
                        'width' => $_GPC['data']['video']['alivideo']['width'] ?? '',
                        'heigh' => $_GPC['data']['video']['alivideo']['height'] ?? '',
                        'min' => $_GPC['data']['video']['alivideo']['max'] ?? '',
                        'max' => $_GPC['data']['video']['alivideo']['max'] ?? '',
                        'yun_type' => 0,
                        'video' => json_encode($createVideo),
                    ];
                    $MaterialModel = new CreateVideo();
                    $res = $MaterialModel->allowField(true)->save($createVideoAddData);
                    if ($res) {
                        $this->createVideos($createVideo, $data, $MaterialModel->id, $_GPC['data']['video']['alivideo']['title']);
                        Queue::push(UploadFileVideo::class, ['id' => $MaterialModel->id]);
                    }
                }
                //处理常规视频
                if (isset($_GPC['data']['video']['list']) && !empty($_GPC['data']['video']['list'])) {
                    $v = new ActivityVideo();
                    //处理活动视频
                    $videoListAll = [];
                    foreach ($_GPC['data']['video']['list'] as $datum) {
                        $infos = ActivityVideo::where(['path'=>$datum['path'],'sale_id'=>$id])->find();
                        if(!$infos && isset($datum['path']) && $datum['path']){
                            $videoListAll[] = [
                                'sale_id' => $id,
                                'status' => 1,
                                'is_download_status' => 1,
                                'download_time' => date('Y-m-d H:i:s'),
                                'synthesis_time' => date('Y-m-d H:i:s'),
                                'title' => $datum['title'],
                                'path' => $datum['path'],
                            ];
                        }
                    }
                    if(!empty($videoListAll)){
                        $v = new ActivityVideo();
                        $res = $v->saveAll($videoListAll);
                        if(!$res) throw new Exception('保存视频数据失败！');
                    }
                }
                $_GPC['data']['video'] = !empty($_GPC['data']['video']['list']) ? json_encode($_GPC['data']['video']['list']) : '';
                $_GPC['data']['replace'] = !empty($_GPC['data']['replace']) ? json_encode($_GPC['data']['replace']) : '';
                $_GPC['data']['card'] = !empty($_GPC['data']['card']) ? json_encode($_GPC['data']['card']) : '';
                $result = pdo_update('sale', $_GPC['data'], array('id' => $id));
                if (!empty($result) || $result === 0) {
                    if ($member['num'] != 0) {
                        $member['num'] = $member['num'] + $data['number'] - $_GPC['data']['number'];
                        $member['num'] != 0 or $member['num'] = -1;
                        pdo_update('member', $member, array('id' => $member['id']));
                    }
                    json_old([], 0, '提交成功！');
                    return jsonp(array('token' => $token));
                    json(array('token' => $token));
                } else {
                    json_old('error', 1, '提交失败！');
                }
            } catch (Exception $exception) {
                json_old('error', 1, $exception->getMessage());
            }

        }
        //获取统计数据
        $data['material_num'] = Db::name('material')->where(['sale_id' => $id])->count('id');
        $data['video_num'] = Db::name('activity_video')->where(['sale_id' => $id, 'status' => 1])->count('id');
        $data['video2_num'] = Db::name('activity_video')->where(['sale_id' => $id, 'status' => 0])->count('id');
        $data['videos_list'] = ActivityVideo::where(['sale_id' => $data['id'], 'status' => 1])->select();
        return jsonp(get_upload_data($data));
    }

    /**
     * 合成视频
     * @throws Exception
     */
    public function createVideos($video, $data, $create_video_id, $title)
    {
        if (!empty($video)) {
            if (isset($video['head']) && !empty($video['head'])) {
                foreach ($video['head'] as $head) {
                    $dataAll[] = [
                        'path' => $head['path'],
                        'sale_id' => $data['id'],
                        'yun_type' => 0,
                        'position' => 0,
                        'create_video_id' => $create_video_id,
                        'title' => $title,
                        'user_id' => $data['member_id'],
//                        'type' => 0,
                    ];
                }
            }

            if (isset($video['tail']) && !empty($video['tail'])) {
                foreach ($video['tail'] as $head) {
                    $dataAll[] = [
                        'path' => $head['path'],
                        'sale_id' => $data['id'],
                        'yun_type' => 0,
                        'position' => 2,
                        'create_video_id' => $create_video_id,
                        'title' => $title,
                        'user_id' => $data['member_id'],
//                        'type' => 'tail',
                    ];
                }
            }

            if (isset($video['list']) && !empty($video['list'])) {
                foreach ($video['list'] as $head) {
                    $dataAll[] = [
                        'path' => $head['path'],
                        'sale_id' => $data['id'],
                        'yun_type' => 0,
                        'position' => 1,
                        'create_video_id' => $create_video_id,
                        'title' => $title,
                        'user_id' => $data['member_id'],
//                        'type' => 'list',
                    ];
                }
            }
        }
        if (!empty($dataAll)) {
            $m = new \app\commons\model\Material();
            $mRes = $m->saveAll($dataAll);
            if (!$mRes) throw new Exception('生成视频失败！');
        }
    }

    public function del()
    {

        $_GPC = input();
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            //删除用户数据
            $result = SaleModel::destroy(function ($query) use ($id) {
                $query->where('id', 'in', $id);
            });
            if ($result) {
                jsont([], 0, '删除成功！');
            }
            jsont([], 1, '删除失败');
        }
        json([], 1, 'error');
    }

    public function aliaddvideo()
    {

        $_GPC = input();
        $data = array();
        return jsonp(get_upload_data($data));
    }

    public function endsale(\app\commons\model\Sale $sale)
    {

        $_GPC = $this->data;
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            $info = $sale->where(['id' => $id])->find();
            if (!$info) jsont([], 1, '数据不存在');
            if ($info['status'] != 0) jsont([], 1, '活动已结束');
            $info->endtime = time() - 86401;
            $info->status = 1;
            $result = $info->save();
            if ($result) {
                jsont([], 0, '结束成功');
            }
            jsont([], 1, '处理失败');
        }
        jsont([], 1, '处理失败');
    }

    public function verifyer()
    {

        $_GPC = $this->data;
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 1);

        $row = SaleVerifyer::alias('v')
            ->join('member m', 'v.member_id=m.id')
            ->field('v.* ,m.avatar,m.nickname')
            ->where(array('v.sale_id' => $_GPC['id']));
        $count = $row->count();
        $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
        return jsonpp($data, $count);
    }

    public function addverifyer()
    {

        $_GPC = input();
        $result = SaleVerifyer::create(['member_id' => $_GPC['member_id'], 'sale_id' => $_GPC['id'], 'createtime' => time()]);
        if ($result) {
            jsont([], 0, '添加成功');
        }
        jsont([], 1, '添加失败');
    }

    public function delverifyer()
    {

        $_GPC = input();
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            $result = SaleVerifyer::destroy(function ($query) use ($id) {
                $query->where('id', 'in', $id);
            });
            if ($result) {
                jsont([], 0, '删除成功');
            } else {
                jsont([], 1, '删除失败');
            }
        }
        jsont([], 1, 'error');
    }

    public function verifyerqr()
    {
        $_GPC = input();
        $code = rand(100000, 999999);
        $url = $this->request->domain(true) . '?merch_code=' . $code;
        //绑定核销员2分钟超时，需要刷新二维码重新扫码绑定
        Redis::redis()->set('douyin:sale:code:' . $code, $_GPC['id'], 120);
//        $qrCode  = new QrCode();
//        $setVersion = $qrCode -> setVersion(5);
//        $flieName = 'liukelk.jpg';//二维码的名字
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';
        ob_start();
        \QRcode::png($url, false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();
        exit($qrcode);
        $_GPC = $this->data;
//        $code = new QRcode();
//        if(is_file('uploads/qrcode/'.$_GPC['id'].'.png')) return jsonp(['url'=>'uploads/qrcode/'.$_GPC['id'].'.png']);
        $code = rand(10000, 99999);
        $register_url = $this->request->domain(true) . '/web/index/bindverifyer?id=' . $_GPC['id'] . 'code=' . $code;
        redis()->set('code:' . $code, $_GPC['id']);
//        $code =  $code->png($register_url,'uploads/qrcode/'.$_GPC['id'].'.png');
        return jsonp(['url' => $register_url]);
        $qrCode = new QrCode($this->request->domain(true) . '/web/index/bindverifyer?id=' . $_GPC['id']);
        $qrCode->setSize(150);
        // 边框宽度
        $qrCode->setMargin(2);
        // 图片格式
//        $qrCode->setWriterByName('png');
        // 字符编码
//        $qrCode->setEncoding('UTF-8');
        // 颜色设置，前景色，背景色(默认黑白)
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        header('Content-Type: ' . $qrCode->getContentType());
        // 容错等级，分为L、M、Q、H四级
        $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
        $sha1 = sha1('yhq6584');
        $path = substr($sha1, 0, 2) . '/' . substr($sha1, 2, 3) . '/';
        $qrcode_dir = '/uploads/' . $path;
        if (!file_exists($qrcode_dir)) mkdir($qrcode_dir, 0777, true);
        $code_path = $qrcode_dir . $sha1 . '.png';
        $code_logo = 'public\uploads\head\20200317\c15342e43d82a8c83604d84195c1d068.jpg';
        $qrCode->setLabel('手机扫一扫', 12);
        //$qrCode->setLogoPath($code_logo);
        $qrCode->setLogoWidth(64);
        $qrCode->writeFile($code_path);
        //  return $this->redirect('Login/indexYhq');
        //  echo date('Y-m-d H:i:s',2437112213);
        echo $path . $sha1 . '.png';
        die;
        require_once '../extend/qrcode/phpqrcode.php';
        $res = QRcode::png($this->request->domain(true) . '/web/index/bindverifyer?id=' . $_GPC['id'], false, 'L', 5, 2);
        dump($res);
        die;
    }

    public function tuiguangqr()
    {
        $_GPC = $this->data;
        $data = pdo_get('sale', array('id' => $_GPC['id']));
        $url = 'https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'] . ",video.data" . '&redirect_uri=' . urlencode($this->request->domain(true) . '/web' . '?id=' . $_GPC['id']);
        return jsonp(['url' => $url]);
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';

        ob_start();
        QRcode::png('https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'] . ",video.data" . '&redirect_uri=' . urlencode($this->request->domain(true) . '/web' . '?id=' . $_GPC['id']), false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();
        exit($qrcode);
    }

    public function tuiguang()
    {

        $_GPC = input();
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';
        $data = pdo_get('sale', array('id' => $_GPC['id']));

        ob_start();
        QRcode::png('https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'] . ",video.data" . '&redirect_uri=' . urlencode($this->request->domain(true) . '/web' . '?id=' . $_GPC['id']), false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();

        $sale = pdo_get('sale', array('id' => $_GPC['id']));
        $poster = json_decode($sale['poster'], true);
        //exit;

        if (($poster) > 0) {
            $config = array('text' => array(), 'image' => array(), 'background' => '', 'stream' => 1);
            $scale = 1;
            foreach ($poster as $key => $value) {
                if ($value['type'] == 'qr') {
                    $config['image'][] = array('url' => $qrcode, 'left' => floatval($value['left']), 'top' => floatval($value['top']), 'right' => 0, 'stream' => 1, 'bottom' => 0, 'width' => floatval($value['width']), 'height' => floatval($value['height']), 'opacity' => 100);
                }
                if ($value['type'] == 'img') {
                    if (stristr($value['src'], 'http') == false) {
                        $value['src'] = $this->request->domain(true) . $value['src'];
                    }
                    $img = ihttp_get($value['src']);
                    $config['background'] = $img['content'];
                    $backgroundInfo = getimagesizefromstring($img['content']);
                    $scale = $backgroundInfo[0] / 320;
                }
            }
            isset($backgroundInfo) or $backgroundInfo = array(320, 504);
            foreach ($config['image'] as $key => $value) {
                $config['image'][$key]['left'] = $scale * $value['left'];
                $config['image'][$key]['top'] = $scale * $value['top'];
                $config['image'][$key]['width'] = $scale * $value['width'];
                $config['image'][$key]['height'] = $scale * $value['height'];
            }
            foreach ($config['text'] as $key => $value) {
                $config['text'][$key]['left'] = $scale * $value['left'];
                $config['text'][$key]['top'] = $scale * $value['top'] + $scale * $value['fontSize'] * 1.5;
                $config['text'][$key]['fontSize'] = $scale * $value['fontSize'];
            }
            $config['width'] = $backgroundInfo[0];
            $config['height'] = $backgroundInfo[1];
            // print_r($config);exit;
            echo createPoster($config);
            exit;
        } else {
            exit($qrcode);
        }
    }

    public function cards()
    {
        try {
            $_GPC = input();
            $page = max(intval($_GPC['page']), 1);
            $limit = max(intval($_GPC['limit']), 10);
            $row = SaleCard::alias('c')
                ->join('member m', 'c.user_id=m.id')
                ->field('c.*,m.avatar,m.nickname')->where(array('c.sale_id' => $_GPC['id']));
            $count = $row->count();
            $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
            return jsonpp($data, $count);
        } catch (Exception $exception) {
            jsont([], 1, $exception->getMessage());
        }

//        $users = $row->paginate($page);
//        jsonp($users);
    }

    public function users()
    {
        try {
            $_GPC = input();
            $page = max(intval($_GPC['page']), 1);
            $limit = max(intval($_GPC['limit']), 10);

            $row = MemberSale::where(array('a.sale_id' => $_GPC['id']))->alias('a')->leftJoin('member m', 'm.id = a.member_id')->field(['a.*', 'm.nickname', 'm.mobile']);
            $count = $row->count();
            $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
            return jsonpp($data, $count);
        } catch (Exception $exception) {
            jsont([], 1, $exception->getMessage());
        }

//        $users = $row->paginate($page);
//        json_old($users);
    }

    public function datas()
    {

        $_GPC = input();
        $where = array('sale_id' => $_GPC['id']);
        $data = Db::name('member_video')
            ->field('SUM(avg_play_duration) AS avg_play_duration , SUM(total_comment) AS total_comment , SUM(total_like) AS total_like , SUM(total_play) AS total_play , SUM(total_share) AS total_share')
            ->where($where)
            ->find();

        $data['avg_play_duration'] = floatval($data['avg_play_duration']);
        $data['total_comment'] = intval($data['total_comment']);
        $data['total_like'] = intval($data['total_like']);
        $data['total_play'] = intval($data['total_play']);
        $data['total_share'] = intval($data['total_share']);
        $data['usernum'] = Db::name('member_sale')->where($where)->count();
        $data['cardnum'] = Db::name('sale_card')->where($where)->count();
        $where['status'] = 1;
        $data['cardstatus1num'] = Db::name('sale_card')->where($where)->count();
        $where['status'] = 0;
        $data['cardstatus0num'] = Db::name('sale_card')->where($where)->count();
        return jsonp($data);
    }

    /**
     * 活动视频
     * @throws \think\exception\DbException
     */
    public function videodata()
    {

        $_GPC = $this->data;

        $_GPC['page'] = isset($_GPC['page']) ? $_GPC['page'] : 1;

        $_GPC['limit'] = isset($_GPC['limit']) ? $_GPC['limit'] : 10;
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 10);

        $row = Db::name('member_video')->where(array('member_id' => $_GPC['mid'], 'sale_id' => $_GPC['sale_id']));
        $count = $row->count();
        $list = $row->page($page, $limit)->order('createtime', 'DESC')->select();

//                foreach($list as $key=>$ll)
//        {
//            $list[$key]['videolist']=json_decode($ll['video'],true);
//			$str_arr=explode(".mp4",str_replace($_SERVER['DOCUMENT_ROOT'],"", $list[$key]['videolist']['path']));
//            $list[$key]['videopath']=$str_arr[0].".mp4";
//
//        }
        return jsonpp($list, $count);
        return jsonpp($list);
    }

    /**
     * 核销优惠券
     * @param SaleCard $saleCard
     */
    public function hexiao(SaleCard $saleCard)
    {

        $_GPC = $this->data;
        $info = $saleCard->where(['id' => $_GPC['id']])->find();
        if (!$info) jsont([], 1, '数据不存在');
        if ($info['status'] != 0) jsont([], 1, '状态错误');
        $info->status = 1;
        $result = $info->save(['status' => 1]);
        if ($result) {
            jsont([], 0, '核销成功');
        }
        jsont([], 1, '核销失败');
    }

}
